import { connect } from 'dva';
import { useEffect, useRef } from 'react';
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min.js';
import { useModel, history } from 'umi';
import goodStorage from 'good-storage';
import defaultSystemSettings from '@/layouts/defaultSystemSettings';
import LoginComponents from './components/Login';
import styles from './style.less';
import qrCodeIcon from '../../assets/images/login/qrcode.png';

const { UserName, Password, Submit } = LoginComponents;

function UserLogin(props) {
  const { dispatch, submitting } = props;
  const formRef = useRef();
  const { setInitialState, initialState } = useModel('@@initialState');

  const handleSubmit = (err, values) => {
    if (err === 'no-err') {
      // 密码加密
      const key =
        'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJZrad51I1vPRoAtzHop3bnMuKS1Z614m8obzURJIGuecqlTXpQlN7i/hXxC5IBuJ/t2PndNvF5QN0VldqFhtIsCAwEAAQ==';
      const { username } = values;
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(key);
      const password = encrypt.encrypt(values.password);

      const callback = async userInfo => {
        await dispatch({
          type: 'userLogin/getMenuData',
          payload: { role: userInfo.role },
        });
        const loginfo = goodStorage.get('loginfo', {});
        setInitialState(loginfo);
      };

      dispatch({
        type: 'userLogin/login',
        payload: { username, password },
        callback,
      });
    }
  };
  const { loginPlatformName } = defaultSystemSettings;

  useEffect(() => {
    const { menuData, isLogin } = initialState;
    if (isLogin) {
      const { path, children: child = [] } = menuData[0] || {};
      history.push(child.length ? child[0].path : path);
    }
  }, []);

  return (
    <div className={styles.main}>
      <div className={styles.middle}>
        <img className={styles.loginTypeIcon} src={qrCodeIcon} alt="" />
        <div className={styles.logo_title}>{loginPlatformName}</div>

        <LoginComponents onSubmit={handleSubmit} ref={formRef}>
          <UserName
            name="username"
            placeholder="请输入用户名"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          />
          <Password
            name="password"
            placeholder="请输入密码"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
            onPressEnter={e => {
              e.preventDefault();
              formRef.curretn.validateFields(handleSubmit);
            }}
          />
          {/* <Captcha
              name="code"
              placeholder="验证码"
              imgUrl={userLogin.captchaImg || ''}
              dispatch={dispatch}
              rules={[
                {
                  required: true,
                  pattern: /^[a-zA-Z0-9]+$/,
                  message: '验证码',
                },
              ]}
            /> */}
          <Submit loading={submitting}>登录</Submit>
        </LoginComponents>
      </div>
    </div>
  );
}

export default connect(({ userLogin, loading, global }) => ({
  global,
  userLogin,
  submitting: loading.effects['userLogin/login'],
}))(UserLogin);
